# -*- coding: utf-8 -*-
import os
import datetime

import botpy
from botpy import logging, BotAPI
from botpy.ext.cog_yaml import read
from botpy.message import GroupMessage
from botpy.types.inline import Keyboard, Button, RenderData, Action, Permission, KeyboardRow
from botpy.types.message import MarkdownPayload, KeyboardPayload
from pool import MyPool


test_config = read(os.path.join(os.path.dirname(__file__), "config.yaml"))

_log = logging.get_logger()


class MyClient(botpy.Client):
    _command_path = "./command.json"

    async def on_ready(self):
        _log.info(f"robot 「{self.robot.name}」 on_ready!")

    async def on_group_at_message_create(self, message: GroupMessage):
        current_time = datetime.datetime.now()
        formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
        if "开启修仙之旅" in message.content:
            my_pool = MyPool()
            user_id = message.author.member_openid
            name = "狗大蟀"
            insert_user = my_pool.add_user(user_id, name)

            message_result = await message._api.post_group_message(
                group_openid=message.group_openid,
                msg_type=0,
                msg_id=message.id,
                content=f"\n欢迎来到璃月修仙：\nID:{insert_user.id}\nOpenID:{insert_user.user_id}"
                        f"\n道号：{insert_user.name}\n加入时间：{insert_user.create_time}")
        else:
            message_result = await message._api.post_group_message(
                group_openid=message.group_openid,
                msg_type=0,
                msg_id=message.id,
                content=f"\n收到了消息：\n{message.content}\n{formatted_time}\n用户ID：{message.author}")

        _log.info(message_result)
        # await send_template_keyboard(self.api, message)
        # await send_self_defined_keyboard(self.api, message)


async def send_template_keyboard(api: BotAPI, message: GroupMessage):
    markdown = MarkdownPayload(content="# 123 \n 今天是个好天气")
    keyboard = KeyboardPayload(id="62")
    await api.post_group_message(group_openid=message.group_openid,
                                 content=f"\n收到了消息：\n{message.content}",
                                 msg_id=message.id,
                                 markdown=markdown,
                                 keyboard=keyboard)


async def send_self_defined_keyboard(api: BotAPI, message: GroupMessage):
    markdown = MarkdownPayload(content="# 标题 \n## 简介 \n内容")
    keyboard = KeyboardPayload(content=build_a_demo_keyboard())
    await api.post_group_message(group_openid=message.group_openid,
                                 content=f"\n收到了消息：\n{message.content}",
                                 msg_id=message.id,
                                 markdown=markdown,
                                 keyboard=keyboard)


def build_a_demo_keyboard() -> Keyboard:
    """
    创建一个只有一行且该行只有一个 button 的键盘
    """
    button1 = Button(
        id="1",
        render_data=RenderData(label="button", visited_label="BUTTON", style=0),
        action=Action(
            type=2,
            permission=Permission(type=2, specify_role_ids=["1"], specify_user_ids=["1"]),
            click_limit=10,
            data="/搜索",
            at_bot_show_channel_list=True,
        ),
    )

    row1 = KeyboardRow(buttons=[button1])
    return Keyboard(rows=[row1])


if __name__ == "__main__":
    # 通过预设置的类型，设置需要监听的事件通道
    # intents = botpy.Intents.none()
    # intents.public_guild_messages=True

    # 通过kwargs，设置需要监听的事件通道
    intents = botpy.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])
